package com.stone.sys.action;

/**
 * 机构管理
 * <pre>
 * @author：JZ
 * @since:2010/02/10
 * </pre>
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.opensymphony.xwork2.Action;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TOrgan;
import com.stone.sys.service.OrganService;
import com.stone.utils.JsonUtils;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;

public class OrganAction extends BaseAction {

	private static final long serialVersionUID = 865527685459140622L;

	private OrganService organService;
	
	// 实体用于修改
	private TOrgan entity = new TOrgan();
	
	// 父节点
	private String parentID;
	
	// 删除时用标示
	private String id;
	
	public String initOrgan() throws AppException  {
		
		List<TOrgan> o = organService.findListByHql(" from TOrgan order by organCode Desc");
		
		if (o.size() > 0) {
			super.getSession().setAttribute("session_parent_id", o.get(0).getParentId());//(TOrgan) super.getSession().getAttribute(IConstant.SESSION_TORGAN)).getParentId()
		} else {
			super.getSession().setAttribute("session_parent_id", 0);
		}
		return Action.SUCCESS;
		
	}
	
	/**
	 * 查询用户菜单
	 * @return
	 * @throws AppException
	 */	
	@SuppressWarnings("unchecked")
	public void getOrgan() throws IOException  {
		
		List<HashMap<String,Object>> listTree;
		
		String where = "";
		
		String organCode = String.valueOf(super.getSession().getAttribute(IConstant.SESSION_TORGAN_CODE));

		// 查询条件OUID很重要
		where += " t.organCode like '%" + organCode + "%'";

		
		// 人员左侧的机构树
		if (null == parentID) {
			
				listTree = organService.getListByDHql(
					"t.id as id, t.organName as text, t.organCode as qtip,t.parentId as parentId", 
					"", 
					null, 
					" order by t.organCode", 
					" TOrgan t");
			
			
		// 维护时根节点
		} else if ("".equals(parentID)) {
		//t.organCode
			listTree= organService.getListByDHql(
					"t.id as id, t.organName as text, '' as qtip,t.parentId as parentId," 
					+ "(case when (select count(o.id) from TOrgan o where o.parentId = t.id)>0 then false else true end) as leaf",
					"", 
					null,  
					" order by t.organCode", 
					" TOrgan t");
			
			// 维护时异步节点
		} else {
	
			listTree = organService.getListByDHql(
					"t.id as id, t.organName as text, '' as qtip,t.parentId as parentId," 
					+ "(case when (select count(o.id) from TOrgan o where o.parentId = t.id)>0 then false else true end) as leaf", 
					"parentId = ? ", 
					new Object[]{Long.parseLong(parentID)}, 
					" order by t.organCode", 
					" TOrgan t");
		}
			
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(listTree, jsonConfig);
        
        super.getResponse().getWriter().print(json.toString());
		
	}
	


	/**
	 * 新建或修改一条记录
	 * @return
	 * @throws AppException
	 */	
	public void save() throws IOException  {
		
		this.organService.save(entity);
		
		super.getResponse().getWriter().print("{success:true}");
	}

	/**
	 * 删除一条记录
	 * @return
	 * @throws AppException
	 */	
	public void delete() throws IOException  {
		
		TOrgan organ  = (TOrgan) organService.findById(Long.parseLong(id), TOrgan.class.getName());
		
		if (organService.getCountByOrgan(organ) > 0) {
			super.getResponse().getWriter().print("{success:0}");
			return;
		}
		
		this.organService.delete(Long.parseLong(id));
		super.getResponse().getWriter().print("{success:1}");
	}
	
	/**
	 * 停用一条记录
	 * @return
	 * @throws AppException
	 */	
	public void recycle() throws IOException  {
		this.organService.updateByHQL("Update TOrgan set state ='0' where id = '" + id + "'", null);
		super.getResponse().getWriter().print("{success:true}");
	}
	
	/**
	 * 查询一条记录
	 * @return
	 * @throws AppException
	 */	
	public void find()  throws IOException  {
		
		TOrgan organ  = (TOrgan) organService.findById(Long.parseLong(id), TOrgan.class.getName());
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON((organ != null ? organ : new TOrgan()), jsonConfig);

        super.getResponse().getWriter().print(json.toString());
	}

	/**
	 * 查询一条记录
	 * @return
	 * @throws AppException
	 */	
	public void findListOrgan()  throws IOException  {
		
		List<TOrgan> l = null;
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
        JSON json;
        
        // 详细信息区县下拉框
		if ("all".equals(super.getRequest().getParameter("organflag"))) {
			l = organService.findListByHql("from TOrgan where length(organCode) = 9");
	        json = JSONSerializer.toJSON(l, jsonConfig);
	        super.getResponse().getWriter().print(json.toString());
	        return;
		} 
		
        // 市 查询用
		if ("1".equals(super.getSession().getAttribute(IConstant.SESSION_ISCITY))) {
			l = organService.findListByHql("from TOrgan where length(organCode) = 9");
	        List<TOrgan> listOrgan = new ArrayList<TOrgan>();
	        TOrgan temp = new TOrgan();
	        temp.setOrganName("全部");
	        listOrgan.add(temp);
	        listOrgan.addAll(l);
	        
	        json = JSONSerializer.toJSON(listOrgan, jsonConfig);
			
	        // 区县
		} else {

			l = organService.findListByHql("from TOrgan where organCode = '" + super.getSession().getAttribute(IConstant.SESSION_TORGAN_CODE).toString() + "'");

			json = JSONSerializer.toJSON(l, jsonConfig);
		}

        super.getResponse().getWriter().print(json.toString());
	}

	public void setOrganService(OrganService organService) {
		this.organService = organService;
	}

	public void setParentID(String parentID) {
		this.parentID = parentID;
	}

	public void setEntity(TOrgan entity) {
		this.entity = entity;
	}
	
	public TOrgan getEntity() {
		return entity;
	}
	
	public void setId(String id) {
		this.id = id;
	}


}
